package com.bc5Neptune.cis.android;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.bc5Neptune.cis.transfer.ByteMessage;
import com.bc5Neptune.cis.transfer.FPSCounter;
import com.bc5Neptune.cis.transfer.TextMessage;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView.SavedState;
import android.widget.Toast;

public class SendImgRecognition extends Activity implements OnClickListener {
	public int defaultPort = 2411;
	public String ip = "192.168.10.187";
	public Socket socketString;
	public Socket socketImage;
	Button btnSend;
	String[] reStr = new String[9];
	String path = "";
	String msgInf = "";
	byte[] bImg = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.send_image);
		//Bundle bdRecInf = this.getIntent().getExtras();
		
		showImg();
		btnSend = (Button) findViewById(R.id.btnSend);
		btnSend.setOnClickListener(this);
		
	    
	}

	/*
	 * 
	 */
	public void showImg() {
		Bundle bdReceive = this.getIntent().getExtras();
		path = bdReceive.getString("1");
//		ip = bdReceive.getString("2");
//	    defaultPort = bdReceive.getInt("3");
		Toast t = Toast.makeText(this, path, 1000);
		t.show();
		ImageView image = (ImageView) findViewById(R.id.imageView1);
		Bitmap bMap = BitmapFactory.decodeFile(path);
		image.setImageBitmap(bMap);
	}

	public void connect() {
		try {
			socketString = new Socket(ip, defaultPort);
			TextMessage msg = new TextMessage(socketString.getInputStream());
			// connect socket image
			socketImage = new Socket(ip, defaultPort);

			if (socketString == socketImage) {
				System.out.println("I'm gona die");
			}
			String strShow = msg.receive();
			System.out.println(strShow);
			sendImage();
			// initlization receive class
			Receive receive = new Receive(socketImage, socketString);
			receive.start();// start listening
			try {
				receive.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			msgInf = receive.getMessage();
			bImg = receive.getbImg();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
    public byte[] bufferedImageToByteArray(Bitmap bufferedImage) {
        //byte[] byteImage = null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bufferedImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] byteImage = stream.toByteArray();
        return byteImage;
    }
	public void sendImage() {
		
		Bitmap image = null;
		image = BitmapFactory.decodeFile(path);
		byte[] byteArray = bufferedImageToByteArray(image);
		try {
			ByteMessage msgByte = new ByteMessage(
					socketImage.getOutputStream(), byteArray);
			msgByte.send();
		} catch (IOException ex) {
			Logger.getLogger(SendImgRecognition.class.getName()).log(
					Level.SEVERE, null, ex);
		}
	}
	
	public void splitString(String msgInf){
		int i = 0;
        
        String receiveServer =msgInf;// "054812$ngoc$abc$hehe$kaka$dsadsa$dwsdwqd$fdsafsa";//msgInf
        StringTokenizer st = new StringTokenizer(receiveServer, "$");
        while(st.hasMoreTokens()){
            reStr[i] = st.nextToken();
            i++;
        }
	}
	public void onClick(View view) {	
		connect();
		splitString(msgInf);
		Intent i = new Intent(getApplicationContext(),ViewImgActivity.class);
		//Log.w("PID", msgInf);
		Toast t = Toast.makeText(this,msgInf,1000);
		t.show();
		Toast t1 = Toast.makeText(this,Receive.messageDis,1000);
		t1.show();
    	Bundle b = new Bundle();
    	b.putString("1",reStr[0]);
    	b.putString("2",reStr[1]);
    	b.putString("3",reStr[2]);
    	b.putString("4",reStr[3]);
    	b.putString("5",reStr[4]);
    	b.putString("6",reStr[5]);
    	b.putString("7",reStr[6]);
    	b.putString("8",reStr[7]);
    	b.putByteArray("9",bImg);
    	i.putExtras(b);
    	startActivity(i);
    	finish();
	}

}

class Receive extends Thread {
	
    Socket socketImage;
    Socket socketString;
    public static String messageDis;
    public static String message;
    private static byte[] bImg;

    public Receive(Socket socketImage, Socket socketString) {
        this.socketImage = socketImage;
        this.socketString = socketString;
    }
    public String getMessage(){
		return messageDis;
    }
    
    public void setMessage(String message){
    	this.messageDis = message;
    }
	public static byte[] getbImg() {
		return bImg;
	}
	public static void setbImg(byte[] bImg) {
		Receive.bImg = bImg;
	}

    @Override
    public void run() {
        //listen to message
        FPSCounter obj = new FPSCounter();
        obj.setFPS(60);//60 frame per second
        while (true) {
            obj.BeginCount();
            try {
                TextMessage msg = new TextMessage(socketString.getInputStream());
                message = msg.receive();
                if (message != null) {
                    System.out.println("Information of this person: " + message);
                    Log.w("message",message);
                    setMessage(message);
                    
                    if (message.charAt(0) != '#') {
                        ByteMessage msgByte = new ByteMessage(socketImage.getInputStream());
                        byte[] b = msgByte.receive();

                        if (b != null) {

                        	setbImg(b);
                            break;
                        }
                       
                    }
                    break;
                }
            } catch (IOException ex) {
                Logger.getLogger(Receive.class.getName()).log(Level.SEVERE, null, ex);
            }
            obj.EndCount();
        }
    }

}
